package org.hero.reptile;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.StrUtil;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class XBiquge_laReptile {

    /* 小说目录URL */
//    private static final String NOVEL_URL = "http://www.biququ.com/html/20494/";
    private static final String NOVEL_URL = "https://www.xbiquge.la/48/48900/";


    /* 章节URL前缀 */
    private static final String CHAPTER_URL_PREFIX = "https://www.xbiquge.la";

    /* 斜杠 */
    private static final String SLASH = "/";

    /* 小说正文段落缩进 */
    private static final String CONTENT_PREFIX = "　　";

    /* 换行 */
    private static final String LINE_FEED = "\n";

    private static final String LINE_FEED_2 = "\n\n";

    private static final String LINE_FEED_3 = "\n\n\n";

    /* 数字  0 */
    private static final int NUMBER_0 = 0;

    private static final int NUMBER_1 = 1;

    private static final int NUMBER_64 = 64;

    /* HTML中的标签 */
    private static final String HTML_TAG_DD = "dd";

    private static final String HTML_TAG_DL = "dl";

    private static final String HTML_TAG_A = "a";

    private static final String HTML_TAG_P = "p";

    /**
     * html 标签的属性
     **/
    /* a的属性href */
    private static final String HTML_TAG_A_ATTR_HREF = "href";


    private static final Map HEADER = new HashMap();

    private static final Logger log = LoggerFactory.getLogger(XBiquge_laReptile.class);

    static {
        HEADER.put("User-Agent", "  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0");
        HEADER.put("Accept", "  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        HEADER.put("Accept-Language", "zh-cn,zh;q=0.5");
        HEADER.put("Accept-Charset", "  GB2312,utf-8;q=0.7,*;q=0.7");
        HEADER.put("Connection", "keep-alive");
    }

    public static void run() throws Exception {

        //List<Chapter> chapterList = new ArrayList<>(NUMBER_64);
        Document document = Jsoup.connect(NOVEL_URL).get();
        Elements h1s = document.getElementsByTag("h1");

        Novel novel = new Novel();
        if (CollUtil.isNotEmpty(h1s)) {
            novel.setNovelName(h1s.get(NUMBER_0).text());
        }

        Element info = document.getElementById("info");
        Elements ps = info.getElementsByTag("p");
        if (CollUtil.isNotEmpty(ps)) {
            novel.setNovelAuthor(ps.get(0).text());
        }

        log.error("开始:" + novel.getNovelName());

        Elements dls = document.getElementsByTag(HTML_TAG_DL);
        if (CollUtil.isNotEmpty(dls)) {
            Element dl = dls.get(NUMBER_0);
            Elements dds = dl.getElementsByTag(HTML_TAG_DD);
            int i = NUMBER_1;
            for (Element dd : dds) {
                Elements as = dd.getElementsByTag(HTML_TAG_A);
                if (CollUtil.isNotEmpty(as)) {
                    Element a = as.get(NUMBER_0);
                    Chapter chapter = new Chapter()
                            .setIndex(i++)
                            .setNovel(novel)
                            .setChapterName(a.text())
                            .setUrl(CHAPTER_URL_PREFIX + a.attr(HTML_TAG_A_ATTR_HREF));
                    addContext(chapter);
                    //chapterList.add(chapter);
                }
            }
        }


    }

    public static Chapter addContext(Chapter chapter) throws Exception {
        /* 正文html中的id值 */
        final String CONTENT = "content";
        //log.error(chapter.getUrl());
        Connection connect = Jsoup.connect(chapter.getUrl());
        connect.headers(HEADER);
        Document document = connect.get();
        Element content = document.getElementById(CONTENT);
//        Elements ps = content.getElementsByTag(HTML_TAG_P);
        StringBuilder builder = new StringBuilder();
        builder.append(chapter.getChapterName());
        builder.append(LINE_FEED);
//        for (Element p : ps) {
//            builder.append(CONTENT_PREFIX);
//            builder.append(p.text());
//            builder.append(LINE_FEED);
//        }

        String text = content.html();
        text = text.replaceAll("<div id=\"content\">", "")
                .replaceAll("</div>", "")
                .replaceAll("&nbsp;&nbsp;&nbsp;&nbsp;", "")
                .replaceAll("\n", "")
                .replaceAll("<!--over-->", "")
                .replaceAll("<p><a href=\"http://koubei.baidu.com/s/xbiquge.la\" target=\"_blank\">亲,点击进去,给个好评呗,分数越高更新越快,据说给新笔趣阁打满分的最后都找到了漂亮的老婆哦!</a>", "")
                .replaceAll("手机站全新改版升级地址：https://wap.xbiquge.la，数据和书签与电脑站同步，无广告清新阅读！</p>", "");
        String[] split = text.split("<br>");
        for (String s : split) {
            if (s.startsWith("<!--go-->")) {
                continue;
            }
            if (StrUtil.isNotEmpty(s)) {
                builder.append(CONTENT_PREFIX);
                builder.append(s);
                builder.append(LINE_FEED);
            }
        }
        builder.append(LINE_FEED);
        FileWriter.create(new File("D://下载小说/" + chapter.getNovel().getNovelName() + ".txt"), Charset.defaultCharset()).append(builder.toString());
        log.info(chapter.getChapterName());
        return chapter;
    }

}
